package middleware

import (
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/request"
	"duoke/utils/response"
	"github.com/gin-gonic/gin"
)

func Goods() gin.HandlerFunc {
	return func(c *gin.Context) {
		req := request.JsonMap(c)
		if req["goodsId"] == nil || req["goodsId"] == "" {
			response.Error(c, "商品ID缺失", nil)
			c.Abort()
			return
		}
		goods, err := service.Goods.GetById(gconv.Int(req["goodsId"]), "")
		if err != nil {
			response.Error(c, err.Error(), nil)
			c.Abort()
			return
		}
		if goods.State == 0 {
			response.Error(c, "该商品已下架", nil)
			c.Abort()
			return
		}
		goods.Sales = service.Goods.Sales(goods.Id)
		goods.Income = service.Goods.Income(goods.Id)
		c.Set("goods", *goods)
		// 更新商品用户
		goodsUser, err := service.GoodsUser.Create(c, goods.Id, gconv.Int(req["fromId"]))
		if err != nil {
			response.Error(c, err.Error(), nil)
			c.Abort()
			return
		}
		c.Set("goodsUser", *goodsUser)
		c.Next()
	}
}
